/*
 * ipassbook 0.6.0
 * Copyright (C)2009 wateray and contributors
 * wateray@gmail.com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package com.wateray.ipassbook.kernel.event;

import java.util.Enumeration;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.wateray.ipassbook.util.log4j.Log;


/**
 * @author wateray
 * @create 2009-5-14
 */
public class IPassbookObserver {
	
	private Logger logger = Log.getLogger(this.getClass());
	
	private static IPassbookObserver observer;
	
	private Vector<IPassbookListener> repository = new Vector<IPassbookListener>();
    
	private IPassbookObserver(){	
	}
	
	public static IPassbookObserver getInstance(){
		if( observer== null){
			observer = new IPassbookObserver();
		}
		return observer;
	}
	public synchronized void addIPassbookListener(IPassbookListener IPassbookListener) {
		repository.addElement(IPassbookListener);
		logger.debug("addIPassbookListener: " + IPassbookListener.getClass().getSimpleName());
	}

	public synchronized void removeIPassbookListener(IPassbookListener IPassbookListener) {
		repository.removeElement(IPassbookListener);
		logger.debug("removeIPassbookListener: " + IPassbookListener.getClass().getSimpleName());
	}

	@SuppressWarnings("unchecked")
	public void notifyEvents(IPassbookEvent iPassbookEvent) {
		Vector<IPassbookListener> tempVector = null;

		synchronized (this) {
			tempVector = (Vector<IPassbookListener>) repository.clone();
			Enumeration e = tempVector.elements();
	
			int size = tempVector.size();
		     while(e.hasMoreElements())
		     {
		    	 IPassbookListener IPassbookListener = (IPassbookListener)e.nextElement();
		    	 logger.debug("IPassbookObserver.notifyEvents "+ (size--)+ " = " + IPassbookListener.getClass().getName());
		    	 IPassbookListener.update(iPassbookEvent);
		    	 
		     }
		}

	}
}
